package com.th.cash.th2.product

import android.text.TextUtils
import androidx.lifecycle.viewModelScope
import com.th.basemodel.base.BaseViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import kotlinx.coroutines.flow.debounce

class ProductVm : BaseViewModel() {

    private val repository by lazy {
        ProductRepository()
    }

    val intentChannel = Channel<ProductIntent>(Channel.UNLIMITED)

    //可变状态数据流（读写）（StateFlow替代LiveData，难道每一个页面都需要定义一个）
    private val _uiState = MutableStateFlow<ProductState>(ProductState.Idle)

    //可观察状态数据流（只读）
    val uiState: StateFlow<ProductState> get() = _uiState

    init {
        viewModelScope.launch {
            intentChannel.consumeAsFlow().debounce(500).collect { value ->
                when (value) {
                    is ProductIntent.Idle -> {

                    }

                    is ProductIntent.GetProductDetail -> {
                        getProductDetail(value.request)
                    }

                    is ProductIntent.InitBaseInfo -> {
                        initBaseInfo(value.request)
                    }

                    is ProductIntent.SaveBaseInfo -> {
                        saveBaseInfo(value.request)
                    }

                    is ProductIntent.InitContactInfo -> {
                        initContactInfo(value.request)
                    }

                    is ProductIntent.SaveContactInfo -> {
                        saveContactInfo(value.request)
                    }

                    is ProductIntent.InitBankInfo -> {
                        initBankInfo(value.request)
                    }

                    is ProductIntent.SaveBankInfo -> {
                        saveBankInfo(value.request)
                    }

                    is ProductIntent.InitIdCard -> {
                        initIdCard(value.request)
                    }

                    is ProductIntent.UploadIdCard ->{
                        uploadIdCard(value.path)
                    }

                    is ProductIntent.SaveIdCard -> {
                        saveIdCard(value.request)
                    }

                    is ProductIntent.GetOrderUrl ->{
                        getOrderUrl(value.request)
                    }

                    else -> {

                    }
                }
            }
        }
    }

    private fun getProductDetail(request: ProductDetailRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.getProductDetail(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理获取产品详情成功后的逻辑
                _uiState.value = ProductState.ProductDetailData(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun initBaseInfo(request: BaseInfoRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.initBaseInfo(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理初始化基础信息成功后的逻辑
                _uiState.value = ProductState.BaseInfoData(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun saveBaseInfo(request: BaseSaveRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val requestParams = mutableMapOf<String, Any?>()

            request.params.forEach {
                requestParams[it.first] = it.second
            }

            requestParams["KiOAYsXOverrelianceWWpzcfA"] = request.KiOAYsXOverrelianceWWpzcfA

            val result = repository.saveBaseInfo(requestParams)

            result.checkResult(success = {
                loadSuccess()
                // 处理保存基础信息成功后的逻辑
                _uiState.value = ProductState.VerifySuccess(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun initContactInfo(request: ContactInfoRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.initContactInfo(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理初始化联系人信息成功后的逻辑
                _uiState.value = ProductState.ContactInfoData(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun saveContactInfo(request: ContactSaveRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val requestParams = mutableMapOf<String, Any?>()

            request.params.forEach {
                requestParams[it.first.first] = it.second.first
                requestParams[it.first.second] = it.second.second
                requestParams[it.first.third] = it.second.third
            }

            requestParams["KiOAYsXOverrelianceWWpzcfA"] = request.KiOAYsXOverrelianceWWpzcfA

            val result = repository.saveContactInfo(requestParams)

            result.checkResult(success = {
                loadSuccess()
                // 处理保存联系人信息成功后的逻辑
                _uiState.value = ProductState.VerifySuccess(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun initBankInfo(request: BankInfoRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.initBankInfo(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理初始化基础信息成功后的逻辑
                _uiState.value = ProductState.BankInfoData(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun saveBankInfo(request: BankSaveRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val requestParams = mutableMapOf<String, Any?>()

            request.params.forEach {
                requestParams[it.first] = it.second
            }

            requestParams["KiOAYsXOverrelianceWWpzcfA"] = request.KiOAYsXOverrelianceWWpzcfA

            val result = repository.saveBankInfo(requestParams)

            result.checkResult(success = {
                loadSuccess()
                // 处理保存基础信息成功后的逻辑
                _uiState.value = ProductState.VerifySuccess(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun initIdCard(request: IdCardRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.initIdCard(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理初始化基础信息成功后的逻辑
                _uiState.value = ProductState.IdCardData(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun uploadIdCard(path: String) {
        val body = getBody(path)

        if (body == null) {
            loadError("อัปโหลดล้มเหลว")
            return
        }

        viewModelScope.launch {
            val result = repository.uploadIdCard(body)

            result.checkResult(success = {
                loadSuccess()
                // 处理保存基础信息成功后的逻辑
                _uiState.value = ProductState.UploadIdCad(it!!)
            }, error = {
                loadError(it)
                _uiState.value = ProductState.UploadIdCadError
            })
        }
    }

    private fun getBody(filePath: String): MultipartBody? {
        if (TextUtils.isEmpty(filePath)) {
            return null
        }

        val file = File(filePath)
        val builder = MultipartBody.Builder()
        val body = RequestBody.create("image/png".toMediaTypeOrNull(), file)
        return builder
            .addFormDataPart("am", file.name, body)
            .setType(MultipartBody.FORM)
            .build()
    }


    private fun saveIdCard(request: IdCardSaveRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val requestParams = mutableMapOf<String, Any?>()

            request.params.forEach {
                requestParams[it.first] = it.second
            }

            requestParams["KiOAYsXOverrelianceWWpzcfA"] = request.KiOAYsXOverrelianceWWpzcfA

            val result = repository.saveIdCard(requestParams)

            result.checkResult(success = {
                loadSuccess()
                // 处理保存基础信息成功后的逻辑
                _uiState.value = ProductState.VerifySuccess(it!!)
            }, error = {
                loadError(it)
            })
        }
    }

    private fun getOrderUrl(request: OrderUrlRequest) {
        viewModelScope.launch {
            loadStartLoading()

            val result = repository.getOrderUrl(request)

            result.checkResult(success = {
                loadSuccess()
                // 处理获取订单数据成功后的逻辑
                _uiState.value = ProductState.ShowDetail(it?.ODKSaOjEmbowHJdsBQj?:"")
            }, error = {
                loadError(it)
            })
        }
    }


}